package cn.bbstone.pisces2.server.handler;

import cn.bbstone.pisces2.comm.BFileCmd;
import cn.bbstone.pisces2.comm.Const;
import cn.bbstone.pisces2.comm.cache.ServerFliIndexCache;
import cn.bbstone.pisces2.config.Config;
import cn.bbstone.pisces2.proto.req.ReqFile;
import cn.bbstone.pisces2.server.fli.FliBuilder;
import cn.bbstone.pisces2.server.util.MsgUtil;
import cn.bbstone.pisces2.util.BFileUtil;
import cn.bbstone.pisces2.util.CtxUtil;
import cn.hutool.core.collection.CollUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ReqListInfoHandler implements ServerHandler {
    private static Logger log = LoggerFactory.getLogger(ReqListInfoHandler.class);

    public ReqListInfoHandler() {
    }


    @Override
    public void handle(ChannelHandlerContext ctx, ReqFile reqFile) {
        long fileNo = reqFile.getFileNo();
        log.debug("recv req fileNo: {}", fileNo);
        // build fli.idx file and send this file info to client
        List<String> filterList = CollUtil.toList(CtxUtil.getConfigModel().getFilter());
        int totalLines = FliBuilder.buildServerFliIndex(BFileUtil.getServerDir(), filterList);
        ServerFliIndexCache.init(Const.SERVER);
        log.debug("File index list size: {}", totalLines);

        Byte msgType = reqFile.getMsgType();
        long reqTs = reqFile.getReqTs();
//        log.debug("send data round({}) cost time: {}", );
        // ---------------------- read server fli index file info
        try {
            MsgUtil.sendFileInfo(ctx, BFileCmd.RSP_LIST_INFO, fileNo, reqTs);
        } catch (Exception e) {
            log.error("handle LIST INFO REQ error.", e);
        }
    }
}
